package com.auto.learning.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.AES;
import com.auto.learning.tools.CommonMethod;

public class HttpHelper {

	private  HttpClient mHttpClient;

	/**
	 * 初始化httpParms
	 */
	public static HttpClient initHttpClient() {
		HttpParams httpParameters;
		httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, HttpCommonInfo.HTTP_CONNECT_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParameters, HttpCommonInfo.HTTP_SO_TIMEOUT);
		HttpClient client = new DefaultHttpClient(httpParameters);
		return client;
	}
	
	
	public static HttpClient initHttpClientLongTime() {
		HttpParams httpParameters;
		httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, HttpCommonInfo.HTTP_CONNECT_TIMEOUT_LONG);
		HttpConnectionParams.setSoTimeout(httpParameters, HttpCommonInfo.HTTP_SO_TIMEOUT_LONG);
		HttpClient client = new DefaultHttpClient(httpParameters);
		return client;
	}

	// public static synchronized HttpClient initHttpClient() {
	// if (mHttpClient == null) {
	// HttpParams params = new BasicHttpParams();
	// //连接超时
	// HttpConnectionParams.setConnectionTimeout(params,
	// HttpCommonInfo.HTTP_CONNECT_TIMEOUT);
	// //请求超时
	// HttpConnectionParams.setSoTimeout(params,
	// HttpCommonInfo.HTTP_SO_TIMEOUT);
	// // 设置HttpClient支持HTTp和HTTPS两种模式
	// SchemeRegistry schReg = new SchemeRegistry();
	// schReg.register(new Scheme("http", PlainSocketFactory
	// .getSocketFactory(), 80));
	// schReg.register(new Scheme("https", SSLSocketFactory
	// .getSocketFactory(), 443));
	// // 使用线程安全的连接管理来创建HttpClient
	// ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
	// params, schReg);
	// mHttpClient = new DefaultHttpClient(conMgr, params);
	// }
	// return mHttpClient;
	// }

	/**
	 * GET交互
	 *
	 * @param url
	 * @param params
	 * @param authorization
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static HttpEntity getInfoByGet(String url, Map<String, Object> params, Context context) throws ClientProtocolException, IOException {
		if (HttpRequestHelper.M_SHOW_LOG) {
			Log.d("url",  url);
		}
		HttpClient client = initHttpClientLongTime();
		String comUrl = null;
		if (params == null) {
			comUrl = url;
		} else {
			comUrl = makeGetURL(url, params);
		}
		HttpGet request = new HttpGet(comUrl);
		request.addHeader("version", "20150331");
		try {
			request.addHeader("client", "Android "
					+ android.os.Build.VERSION.SDK_INT + " AppVersion:"
					+ CommonMethod.getVersionName(context));
		} catch (Exception e) {

		}
		return returnHttpBackInfo(request, client);
	}

	/**
	 * GET交互JSON
	 *
	 * @param url
	 * @param params
	 * @param authorization
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static HttpEntity getInfoByGetByHeader(String url,
			Map<String, Object> params, Context context, long fileLength)
			throws ClientProtocolException, IOException {
		Log.d("url", url);
		HttpClient client = initHttpClient();
		String comUrl = null;
		if (params == null) {
			comUrl = url;
		} else {
			comUrl = makeGetURL(url, params);
		}
		HttpGet request = new HttpGet(comUrl);
		request.addHeader("RANGE", "bytes=" + fileLength + "-");
		return returnHttpBackInfo(request, client);
	}

	/**
	 * POST交互L
	 *
	 * @param url
	 * @param params
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 */
	public static HttpEntity getInfoByPost(String url, List<NameValuePair> params, Context context)
			throws ClientProtocolException, IOException, JSONException {
		/*if (params != null) {
			params.add(new BasicNameValuePair("reqTime", System.currentTimeMillis()+""));
		}*/
		if (HttpRequestHelper.M_SHOW_LOG) {
			Log.d("url", HttpCommonInfo.URL + url);
			for (int i = 0; i < params.size(); i++) {
				Log.d("param", params.get(i).getName()+">>>"+params.get(i).getValue());
			}
		}
		HttpClient client = initHttpClient();
		HttpPost request = new HttpPost(HttpCommonInfo.URL + url);
		if (params != null && params.size() > 0) {
			for (int i = 0; i < params.size(); i++) {
				String name = params.get(i).getName();
				String valueAes = AES.encrypt(params.get(i).getValue());
				BasicNameValuePair bnvp = new BasicNameValuePair(name, valueAes);
				params.remove(i);
				params.add(i, bnvp);
			}
			HttpEntity httpentity = new UrlEncodedFormEntity(params, "UTF-8");
			request.setEntity(httpentity);
		}
		request.addHeader("version", "20150331");
		try {
			request.addHeader("client", "Android "
					+ android.os.Build.VERSION.SDK_INT + " AppVersion:"
					+ CommonMethod.getVersionName(context));
		} catch (Exception e) {

		}
		return returnHttpBackInfo(request, client);
	}

	/**
	 * 返回获取HTTP返回信息
	 *
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static HttpEntity returnHttpBackInfo(HttpRequestBase request,
			HttpClient client) throws ClientProtocolException, IOException {
		HttpResponse httpResponse = null;
		httpResponse = client.execute(request);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {
			return httpResponse.getEntity();
		} else {
			return null;
		}
	}

	/**
	 * 把返回的entity转换成String
	 *
	 * @param entity
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static String entity2String(HttpEntity entity) throws UnsupportedEncodingException, IllegalStateException, IOException, NullPointerException {
		BufferedReader reader = null;
		reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
		String line;
		StringBuffer temp = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			temp.append(line);
		}
		String result=AES.decrypt(temp.toString());
		if (HttpRequestHelper.M_SHOW_LOG) {
			Log.d("result", result+"");
		}
		return result;
	}

	/**
	 * 返回URL
	 *
	 * @param p_url
	 * @param params
	 * @return
	 */
	private static String makeGetURL(String p_url, Map<String, Object> params) {
		StringBuilder url = new StringBuilder(p_url);
		if (url.indexOf("?") < 0)
			url.append('?');

		for (String name : params.keySet()) {
			url.append('&');
			url.append(name);
			url.append('=');
			url.append(AES.encrypt(String.valueOf(params.get(name))));
			// 不做URLEncoder处理
			// url.append(URLEncoder.encode(String.valueOf(params.get(name)),
			// UTF_8));
		}
		return url.toString().replace("?&", "?");
	}
	
	public static void executeHttpRequest(final Context _context,final String _tag,final String _url,final List<NameValuePair> _params,final Handle _handle){
		Pool.getPool().execute(new Runnable() {
			@Override
			public void run() {
				if (HttpRequestHelper.getUserId(_context)) {
					ResponeResult responeResult = new ResponeResult();
					try {
						HttpEntity entity = getInfoByPost(_url, _params, _context);
						String _result = entity2String(entity);
						JSONObject jsonResult = new JSONObject(_result);
						JSONObject result = jsonResult.getJSONObject(HttpCommonInfo.RESULT);
						int code = result.getInt(HttpCommonInfo.RESULT_CODE);
						String msg = result.getString(HttpCommonInfo.RESULT_MSG);
						responeResult.setCode(code);
						responeResult.setMsg(msg);
						responeResult.setTag(_tag);
						if (code == 0) {
							responeResult.setData(jsonResult.getString(HttpCommonInfo.DATA));
							// _handle.obtainMessage(-100, responeResult).sendToTarget();
							EventBus.getEventBus(_tag).post(responeResult);
						} else {
							_handle.sendEmptyMessage(-100);
						}
					} catch (ClientProtocolException e) {
						e.printStackTrace();
						responeResult = null;
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						responeResult = null;
					} catch (IOException e) {
						e.printStackTrace();
						responeResult = null;
					} catch (JSONException e) {
						e.printStackTrace();
						responeResult = null;
					}
				}
			}
		});
	}
	
}
